package classification.geneticAlgorithm;

import java.util.Random;

public class GeneticAlgorithmWithLevel extends GeneticAlgorithm
{
    /* you should guarantee the mutation num is bigger than 1 */
    private final double MUTATION_RATIO = 0.01;

    /* you should guarantee the crossover pair is a integer */
    private int          DNALength      = 0;
    private int          XMLElemNum     = 0;

    public GeneticAlgorithmWithLevel(int initDNALength, int initXMLElemNum)
    {
        super(initDNALength, initXMLElemNum);
        this.DNALength = initDNALength;
        this.XMLElemNum = initXMLElemNum;
    }

    public void init(Individual[] geneticPool)
    {
        Random rand = new Random();
        for (int indvNum = 0; indvNum < geneticPool.length; indvNum++)
        {
            geneticPool[indvNum] = new Individual(this.DNALength);
            int DNAPos = 0;
            for (int i = 0; i < this.XMLElemNum; i++)
            {
                for (int j = i; j < this.XMLElemNum; j++)
                {
                    if (i == j)
                    {
                        geneticPool[indvNum].DNA[DNAPos] = 4;
                    }
                    else
                    {
                        geneticPool[indvNum].DNA[DNAPos] = rand.nextInt(5);
                    }
                    DNAPos++;
                }
            }
        }
    }

    public void mutation(Individual[] geneticPool)
    {
        Random rand = new Random();
        int indvNum = 0;
        int mutationPos = 0;
        for (int mutationNum = 0; mutationNum < geneticPool.length
                * this.MUTATION_RATIO; mutationNum++)
        {
            indvNum = rand.nextInt(geneticPool.length);
            mutationPos = rand.nextInt(this.DNALength);

            int oldValue = geneticPool[indvNum].DNA[mutationPos];
            int newValue = (oldValue + 1) % 5;
            geneticPool[indvNum].DNA[mutationPos] = newValue;
        }
    }
}
